/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package homedatasender;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.security.Security;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.swing.JOptionPane;
import org.antlr.stringtemplate.StringTemplate;
import org.antlr.stringtemplate.language.DefaultTemplateLexer;

/**
 *
 * @author tadas
 */
public class Sender {

    protected DataEntry _data;

    public void setData(DataEntry data) {
        _data = data;
    }

    public void send() throws Throwable {
        {
            String template = "";
            try {
                InputStream in = getClass().getResourceAsStream("/homedatasender/resources/mail.st");
                StringBuilder fileData = new StringBuilder(1000);

                BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
                char[] buf = new char[1024];
                int numRead = 0;
                while ((numRead = reader.read(buf)) != -1) {
                    fileData.append(buf, 0, numRead);
                }
                reader.close();
                template = fileData.toString();
            } catch (IOException ioe) {
                System.err.println(ioe.getMessage());
            }

            org.jdesktop.application.ResourceMap resourceMap =
                    org.jdesktop.application.Application.getInstance(homedatasender.HomeDataSenderApp.class).
                    getContext().getResourceMap(Sender.class);

            String mailHost = Config.getInstance().getData().getSmtpServer();

            ///////// set this variable to be your desired email recipient

            String to = Config.getInstance().getData().getDestEmail();


            String from = Config.getInstance().getData().getSourceEmail();
            String subject = resourceMap.getString("subject.text");

            StringTemplate body = new StringTemplate(template, DefaultTemplateLexer.class);
            body.setAttribute("night", _data.getNaktiesElektra());
            body.setAttribute("day", _data.getDienosElektra());
            body.setAttribute("gas", _data.getDujos());
            body.setAttribute("cold", _data.getSaltasVanduo());
            body.setAttribute("hot", _data.getKarstasVanduo());
            Locale loc = new Locale("lt");
            DateFormat df = DateFormat.getDateInstance(DateFormat.FULL, loc);
            body.setAttribute("date", df.format(_data.getData()));

//            Charset.

            try {

                //Get system properties
                Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

                Properties props = new Properties();
                props.setProperty("mail.transport.protocol", "smtp");
                props.setProperty("mail.host", mailHost);
                props.put("mail.smtp.auth", "true");
                props.put("mail.smtp.port", "465");
                props.put("mail.smtp.socketFactory.port", "465");
                props.put("mail.smtp.socketFactory.class",
                        "javax.net.ssl.SSLSocketFactory");
                props.put("mail.smtp.socketFactory.fallback", "false");
                props.setProperty("mail.smtp.quitwait", "false");

                Session session = Session.getDefaultInstance(props,
                        new javax.mail.Authenticator() {

                            @Override
                            protected PasswordAuthentication getPasswordAuthentication() {
                                return new PasswordAuthentication(
                                        Config.getInstance().getData().getSmtpLogin(),
                                        Config.getInstance().getData().getSmtpPassword());
                            }
                        });

                MimeMessage message = new MimeMessage(session);
                message.setFrom(new InternetAddress(from));
                message.setRecipients(Message.RecipientType.TO,
                        new InternetAddress[]{
                            new InternetAddress(to)
                        });

                message.setSubject(subject);
                String bb = body.toString();
                MimeBodyPart messagePart = new MimeBodyPart();

                MimeMultipart multipart = new MimeMultipart();
                multipart.addBodyPart(messagePart);
                messagePart.setText(bb, "UTF-8");
                messagePart.setHeader("Content-Type", "text/plain; charset=\"utf-8\"");
                messagePart.setHeader("Content-Transfer-Encoding", "quoted-printable");

                message.setContent(multipart);
                message.setSentDate(new Date());

                Transport.send(message);


            } catch (Throwable t) {
                System.out.println(t.getMessage());
                throw t;
            }


        }

    }
}
